//
//  JXProdDetailCtl.m
//  JiaoX
//
//  Created by yinqy on 15/4/13.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXProdDetailCtl.h"
#import "HomeDataTool.h"
#import "ProductDetail.h"
#import "SelfItemInfo.h"
#import "SelfArrowItemInfo.h"
#import "ProdDetailHeaderView.h"
#import "SelfItemInfo.h"
#import "ProdDetailsUitls.h"
#import "ProdDetailFooterView.h"
#import "CartView.h"
#import "ProdSkuView.h"
#import "JXProdComtController.h"
#import "JXTestViewController.h"
#import "JXLoginRegistCheckController.h"
#import "JXNavigationController.h"
#import "AddProdToCartUtil.h"
#import "AnimUtils.h"
#import "ProdDetailItemView.h"
#import "SelfItemCell.h"
#import "HomeReviewsView.h"
#import "JXLookOtherPlayCtl.h"


#define BOTTOM_VIEW_HEIGHT 49
#define BUYBTN_HEIGHT 35
#define BUYBTN_WIDTH 120
#define COLLECTBTN_WIDTH 24

@interface JXProdDetailCtl ()<ProdSkuViewDelegate>
{
    ProdDetailHeaderView *_prodHeaderView;
    ProdDetailFooterView *_prodFooterView;
    UIView *_bottomView;
    UIWebView *_webView;
    
    ProdSkuView *_skuView;
    UIView *_bgView;//这个sku出来之后的背景
    UITapGestureRecognizer *_gestureColseSku;
    
    CartView *_cartView;
    UIButton *_buyBtn;
    UIButton *_collectBtn;
    
    UIImageView *_animImage;
    
}
@property (nonatomic,weak)UIScrollView *scrollView;
@property (nonatomic,copy)NSString *prodId;
@property (nonatomic,strong)CartInfoDao *cartDao;
@property (nonatomic,strong)ProductDetail *prodDetail;
@end

@implementation JXProdDetailCtl

-(instancetype)initWithPordId:(NSString *)prodId
{
    self = [super init];
    if (self) {
        self.prodId = prodId;
        self.cartDao  =[[CartInfoDao alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:JXGlobalColorBg];
    [self initView];
    [self requestData];
    
    
    
}

-(void)initView{
    self.title = @"商品详情";
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, JXScreenW, JXScreenH-BOTTOM_VIEW_HEIGHT)];
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, JXScreenH-BOTTOM_VIEW_HEIGHT, JXScreenW, BOTTOM_VIEW_HEIGHT)];
    [self.view addSubview:_bottomView];
    UIView *view = [[UIView alloc]init];
    [view setFrame:CGRectMake(0, 0, JXScreenW, 0.5)];
    [view setBackgroundColor:SEPARATORCOLOR];
    [_bottomView addSubview:view];
    
    _cartView = [[CartView alloc]initWithImage:@"ic_prod_cart"];
    [_cartView setFrame:CGRectMake(JXPublicInset, (BOTTOM_VIEW_HEIGHT-_cartView.height)*0.5, _cartView.width, _cartView.height)];
    [_cartView addTarget:self action:@selector(toCartCtrl) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_cartView];
    
    _buyBtn = [[UIButton alloc]init];
    [_buyBtn setTitle:@"立即抢购" forState:UIControlStateNormal];
    [_buyBtn setTitle:@"已抢光" forState:UIControlStateDisabled];
    [_buyBtn.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:[DimensUtils getScaleX:16]]];
    [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_buyBtn setContentMode:UIViewContentModeCenter];
    [_buyBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
    [_buyBtn setBackgroundImage:[UIImage resizedImage:@"btn_disable_bg"] forState:UIControlStateDisabled];
    [_buyBtn setFrame:CGRectMake((JXScreenW-BUYBTN_WIDTH)/2, (BOTTOM_VIEW_HEIGHT-BUYBTN_HEIGHT)/2, BUYBTN_WIDTH, BUYBTN_HEIGHT)];
    [_bottomView addSubview:_buyBtn];
    
    _collectBtn = [[UIButton alloc]init];
    [_collectBtn setBackgroundImage:[UIImage imageNamed:@"ic_uncollect"] forState:UIControlStateNormal];
    [_collectBtn setBackgroundImage:[UIImage imageNamed:@"ic_collect"] forState:UIControlStateSelected];
    [_collectBtn setFrame:CGRectMake(JXScreenW-JXPublicInset-COLLECTBTN_WIDTH, (BOTTOM_VIEW_HEIGHT-COLLECTBTN_WIDTH)/2, COLLECTBTN_WIDTH, COLLECTBTN_WIDTH)];
    [_collectBtn addTarget:self action:@selector(coolectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_collectBtn];
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(JXScreenW, NavHeight, JXScreenW, JXScreenH-NavHeight)];
    [self.view addSubview:_webView];
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(webViewSwipe:)];
    [_webView addGestureRecognizer:swipe];
}



-(void)requestData{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    [HomeDataTool getProdDetailWithProdId:self.prodId success:^(ProductDetail *result) {
        [HUD hide:YES];
        if (ISBLANK(result.data)) {
            _prodDetail = result;
            [self inflateData];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
        [HUD hide:YES];
    }];
}


-(void)inflateData{
    
    CGFloat maxY = 0;
    _prodHeaderView = [[ProdDetailHeaderView alloc]init];
    [_prodHeaderView setProdDetail:_prodDetail];
    [self.scrollView addSubview:_prodHeaderView];
    maxY = CGRectGetMaxY(_prodHeaderView.frame);
    
    if (_prodDetail.prodSub.count>1) {
        ProdDetailItemView *skuItem = [[UINib nibWithNibName:@"ProdDetailItemView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil][0];
        [skuItem setWidth:JXScreenW];
        [skuItem setY:maxY];
        SelfItemInfo *skuItemInfo = [SelfArrowItemInfo itemWithIcon:@"ic_sku_item" title:@"选择款式"];
        [skuItemInfo setOperation:^{
            [self openSkuView];
        }];
        [skuItem setItemInfo:skuItemInfo];
        [self.scrollView addSubview:skuItem];
        maxY = CGRectGetMaxY(skuItem.frame);
    }
    

    ProdDetailItemView *picItem = [[UINib nibWithNibName:@"ProdDetailItemView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil][0];
    [picItem setWidth:JXScreenW];
    [picItem setY:maxY];
    SelfItemInfo *picItemInfo = [SelfArrowItemInfo itemWithIcon:@"ic_pic_item" title:@"图文详情"];
    [picItemInfo setOperation:^{
        //图文详情
        [UIView animateWithDuration:0.3 animations:^{
            _webView.x = 0;
        } completion:^(BOOL finished) {
            if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
                self.navigationController.interactivePopGestureRecognizer.enabled = NO;
            }
        }];
    }];
    [picItem setItemInfo:picItemInfo];
    [self.scrollView addSubview:picItem];
    maxY = CGRectGetMaxY(picItem.frame);
    
    
    //判断是否有“看别人怎么玩”
    if (_prodDetail.reviews) {
        ProdDetailItemView *lookItem = [[UINib nibWithNibName:@"ProdDetailItemView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil][0];
        [lookItem setWidth:JXScreenW];
        [lookItem setY:maxY];
        SelfItemInfo *lookItemInfo = [SelfArrowItemInfo itemWithIcon:@"ic_look_item" title:@"看看大家怎么玩"];
        [lookItem setItemInfo:lookItemInfo];
        [lookItemInfo setOperation:^{
            JXLookOtherPlayCtl *ctl = [[JXLookOtherPlayCtl alloc]initWithNibName:@"JXLookOtherPlayCtl" bundle:[NSBundle mainBundle]];
            ctl.prodId = self.prodId;
            [self.navigationController pushViewController:ctl animated:YES];
        }];
        [self.scrollView addSubview:lookItem];
        maxY = CGRectGetMaxY(lookItem.frame);
        
        HomeReviewsView *homeProdView = [[HomeReviewsView alloc]initWithWidth:JXScreenW-20];
        [homeProdView setReviews:_prodDetail.reviews];
        [homeProdView setX:20];
        [homeProdView setY:maxY];
        [self.scrollView addSubview:homeProdView];
         maxY = CGRectGetMaxY(homeProdView.frame);
        
        UIView *spliteView = [[UIView alloc]initWithFrame:CGRectMake(10, maxY, JXScreenW, 0.5)];
        [spliteView setBackgroundColor:SEPARATORCOLOR];
        [self.scrollView addSubview:spliteView];
        maxY = CGRectGetMaxY(spliteView.frame);
    }
    
    ProdDetailItemView *comtItem = [[UINib nibWithNibName:@"ProdDetailItemView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil][0];
    [comtItem setWidth:JXScreenW];
    [comtItem setY:maxY];
    SelfItemInfo *comtItemInfo = [SelfArrowItemInfo itemWithIcon:@"ic_comt_item" title:@"达人交流"];
    if (_prodDetail.prodCommentCount) {
        [comtItemInfo setSubtitle:[NSString stringWithFormat:@"%d人在聊这货",_prodDetail.prodCommentCount]];
    }else{
        [comtItemInfo setSubtitle:@"抢占处女贴"];
    }
    [comtItemInfo setOperation:^{
        JXProdComtController *ctr = [JXProdComtController initWithProductId:self.prodId];
        [self.navigationController pushViewController:ctr animated:true];
    }];
    [comtItem setItemInfo:comtItemInfo];
    [self.scrollView addSubview:comtItem];
    maxY = CGRectGetMaxY(comtItem.frame);
    
    
    
    _prodFooterView = [[ProdDetailFooterView alloc]initWithComtInfo:_prodDetail.prodComment];
    [_prodFooterView setY:maxY];
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toProdComt)];
    [_prodFooterView addGestureRecognizer:singleTap1];
    [self.scrollView addSubview:_prodFooterView];
    maxY = CGRectGetMaxY(_prodFooterView.frame);
    
    //设置sku与图文详情
    _skuView = [[ProdSkuView alloc]initWithProdDetail:_prodDetail];
    [_skuView setDelegate:self];
    [[UIApplication sharedApplication].keyWindow addSubview:_skuView];
    
    _bgView = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.frame];
    [_bgView setBackgroundColor:[UIColor blackColor]];
    [_bgView setAlpha:0.01];
    _gestureColseSku = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeSkuView)];
    
    [_collectBtn setSelected:_prodDetail.isMark];
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_prodDetail.prodDetailUrl]]];
    
    [_buyBtn addTarget:self action:@selector(buyBtnClick) forControlEvents:UIControlEventTouchUpInside];
    if ([_prodDetail isCanBuy]==0) {
        [_buyBtn setEnabled:NO];
    }
    
    [self.scrollView setContentSize:CGSizeMake(JXScreenW, maxY)];
}


-(void)coolectBtnClick:(UIButton *)btn{
    if (TOKEN) {
        [self collectProd:!_collectBtn.selected];
    }else{
        //跳到登录页面
        JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginRegistCheckController alloc]init]];
        [self presentViewController:nav animated:YES completion:^{}];
    }
    
}
-(void)collectProd:(BOOL)isMark{
    if (_prodDetail==nil) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"商品加载出错"];
    }
    [HomeDataTool collectProdWithProdId:[NSString stringWithFormat:@"%d",_prodDetail.prodId] isMark:isMark success:^(JXBaseResponse *result) {
        if ([Utils isBlankString:result.data]) {
            [DialogUtils showTipsWithView:self.navigationController.view String:isMark?@"收藏成功":@"取消成功"];
            _collectBtn.selected = !_collectBtn.selected;
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
        
    } failure:^(NSError *error) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"操作失败"];
    }];
}



/**
 *  更新购物车数量
 */
-(void)updateCartViewNum{
    [_cartView setNum:[_cartDao queryProdsCount]];
}

/**
 *  打开skuView
 */
-(void)openSkuView{
    if (_skuView.x == SKU_MARGINLEFT)return;
    [[UIApplication sharedApplication].keyWindow insertSubview: _bgView belowSubview:_skuView];
    [UIView animateWithDuration:0.3 animations:^{
        _skuView.x = SKU_MARGINLEFT;
        _bgView.alpha = 0.6;
    } completion:^(BOOL finished) {
        [_bgView addGestureRecognizer:_gestureColseSku];
    }];
}

/**
 *  关闭skuView
 */
-(void)closeSkuView{
    if (_skuView.x == JXScreenW)return;
    
    [UIView animateWithDuration:0.3 animations:^{
        _skuView.x = JXScreenW;
        _bgView.alpha = 0.01;
    } completion:^(BOOL finished) {
        //在这清除sku选择项
        [_skuView clearSelected];
        [_bgView removeGestureRecognizer:_gestureColseSku];
        [_bgView removeFromSuperview];
    }];
}

-(void)webViewSwipe:(UISwipeGestureRecognizer *)swipe{
    if (swipe.direction==UISwipeGestureRecognizerDirectionRight) {
        [self closeWebView];
    }
}

-(void)closeWebView{
    [UIView animateWithDuration:0.3 animations:^{
        _webView.x = JXScreenW;
    } completion:^(BOOL finished) {
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        }
    }];
}

-(void)toCartCtrl{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"to_cartctrl" object:nil];
}

-(void)toProdComt{
    JXProdComtController *ctr = [JXProdComtController initWithProductId:self.prodId];
    [self.navigationController pushViewController:ctr animated:true];
}


/**
 *  sku里面的btn点击了
 *
 *  @param count
 */
- (void)buyBtnClickWtihCount:(NSUInteger)count{
    // 首选判断是否有一个选中
    if (TOKEN) {//代表登录过
        //向服务器提交数据
        if ([AddProdToCartUtil assertAddCart:self.navigationController.view productDetail:_prodDetail dao:_cartDao addNumber:count selectSkuPosition:[_skuView getSelectIndex]]) {
            [AddProdToCartUtil postProdToServer:self.navigationController.view productDetail:_prodDetail selectSkuPosition:[_skuView getSelectIndex] prodCount:count ctrl:self];
        }
    }else{
        if ([AddProdToCartUtil assertAddCart:self.navigationController.view productDetail:_prodDetail dao:_cartDao addNumber:count selectSkuPosition:[_skuView getSelectIndex]]) {// 判断活动的商品
            //直接开始动画
            [self startShopCartAnim];
        }
    }
}
/**
 *  商品详情页面的购买按钮点击了
 */
-(void)buyBtnClick{
    [_skuView.calcView setNum:1];
    // 首选判断是否有一个选中
    if([_skuView hasOneChecked]){
        [self buyBtnClickWtihCount:[_skuView.calcView getNum]];
    }else{
        //滑出sku页面
        [self openSkuView];
    }
}

-(void)commitSuccess{
    //这个地方需要执行动画
    [self startShopCartAnim];
}

-(void)commitFailure{
    [DialogUtils showTipsWithView:self.navigationController.view String:@"添加商品失败"];
}

-(void)startShopCartAnim{
    //关闭sku
    [self closeSkuView];
    //添加到数据库
    [AddProdToCartUtil addProdToDb:_prodDetail.prodSub[_skuView.getSelectIndex] prodDetail:_prodDetail dao:_cartDao prodCount:[_skuView.calcView getNum]];
    
    //执行加入购物车动画.动画执行完毕更新购物车数量图标
    NSInteger tag = _prodDetail.prodImages.count>1?1001:1000;
    UIImage *image = ((UIImageView *)[_prodHeaderView.bannerView.scrollView viewWithTag:tag]).image;
    if (image==nil) {
        image = [UIImage imageNamed:@"ic_launcher"];
    }
    _animImage = [[UIImageView alloc]initWithImage:image];
    _animImage.size = CGSizeMake(JXScreenW/2, JXScreenW/2);
    [_animImage.layer setCornerRadius:JXScreenW/4];
    _animImage.layer.masksToBounds = YES;
    _animImage.center = _prodHeaderView.center;
    [self.view addSubview:_animImage];
    [AnimUtils addToCartAnim:_animImage startView:_prodHeaderView.bannerView endView:_cartView delegate:self adverse:1];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [_animImage removeFromSuperview];
    //更新购物车图标
    [self updateCartViewNum];
}
@end
